// useTableScroll.js
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';

export default function useTableScroll(tableDataRef, tableContainerRef, bottomMargin = 34) {
  const tableScroll = ref({ x: "max-content" });

  // 计算表格高度的函数
  const calculateTableHeight = async () => {
    if (!tableDataRef.value) return;

    await nextTick();
    const tableContainer = tableContainerRef.value;
    if (!tableContainer) return;

    // 获取容器到顶部的距离
    const containerRect = tableContainer.getBoundingClientRect();
    const topOffset = containerRect.top;

    // 计算分页器的高度（估计值为40px）
    const paginationHeight = 40;

    // 计算表格可用高度：视窗高度 - 顶部偏移 - 分页器高度 - 底部边距
    const availableHeight = Math.max(window.innerHeight - topOffset - paginationHeight - bottomMargin, 200); // 确保最小高度为200px

    // 设置表格滚动，确保表格不会导致页面出现滚动条
    tableScroll.value = {
      x: "max-content",
      y: `${availableHeight}px`
    };
  };

  // 监听数据变化时重新计算高度
  watch(() => tableDataRef.value, calculateTableHeight, { deep: true });

  // 监听窗口大小变化
  const handleResize = () => {
    calculateTableHeight();
  };

  onMounted(() => {
    calculateTableHeight();
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });

  return {
    tableScroll,
  };
}